const Game = require('../model/game.model');

// 使用模糊查询需要先引入Op
const seq = require('sequelize');
const Op = seq.Op;

// 服务层 读写数据库
class GameService {
    // 添加游戏
    async createGame(game_name, game_desc, game_detail, game_url, banner_url) {
        // Game.create({
        //     game_name: game_name,
        //     game_desc: game_desc
        // });
        // 属性和值一样可以简写
        let res = await Game.create({game_name, game_desc, game_detail, game_url, banner_url});
        return res;
    }

    async getGameInfo({id, game_name, game_desc, flag, pageInfo}) {
        let whereObj = {};
        id && Object.assign(whereObj, {id});
        game_desc && Object.assign(whereObj, {game_desc});
        flag && Object.assign(whereObj, {flag});

        game_name && Object.assign(whereObj, {
            game_name: {
                [Op.like]: `%${game_name}%`
            },
        });
        // 查数量
        let count = await Game.count({where: whereObj});
        let res;
        if (count !== 0) {
            let _pageInfo = {};
            if (pageInfo) {
                let {pageIndex, pageSize} = JSON.parse(pageInfo);
                _pageInfo = {
                    limit: pageSize,
                    offset: (pageIndex - 1) * pageSize
                }
            }
            res = await Game.findAll({
                where: whereObj,
                ..._pageInfo
            });
        }
        return {list: res, count: count} || null;
    }

    async updateGameInfo({id, game_name, game_desc, game_detail, game_url, banner_url, flag}) {

        let whereObj = {id};
        let newGame = {};
        game_name && Object.assign(newGame, {game_name});
        game_desc && Object.assign(newGame, {game_desc});
        game_detail && Object.assign(newGame, {game_detail});
        game_url && Object.assign(newGame, {game_url});
        banner_url && Object.assign(newGame, {banner_url});
        flag && Object.assign(newGame, {flag});
        let res = await Game.update(newGame, {
            where: whereObj
        });
        return res[0] > 0;
    }
}

module.exports = new GameService();